package com.skywolf.chem.tencent.service;

import com.skywolf.chem.utils.SysConfig;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.live.v20180801.LiveClient;
import com.tencentcloudapi.live.v20180801.models.DescribeLivePlayAuthKeyRequest;
import com.tencentcloudapi.live.v20180801.models.DescribeLivePlayAuthKeyResponse;
import com.tencentcloudapi.live.v20180801.models.DescribeLivePushAuthKeyRequest;
import com.tencentcloudapi.live.v20180801.models.DescribeLivePushAuthKeyResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;

/**
 * Created by pei_pei on 2021/1/22.
 */
@Service
public class LiveAuth {
    Logger logger = LoggerFactory.getLogger(LiveAuth.class);
    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};


    public String getPushUrl(Long liveId) {
        String push_domain = SysConfig._this.getProperty("tencent_cdn.push_live");
        String pushAuthKey = getAuthKey("push");
        if(pushAuthKey == null){
            return null;
        }
        String safeKey = getSafeUrl(pushAuthKey,liveId+"",null);
        String input = new StringBuilder().
                append("rtmp://"+push_domain+"/").
                append("live/").
                append(liveId+"?").
                append(safeKey).toString();
        return input;
    }

    public String getPullUrl(Long liveId) {
        String pull_domain = SysConfig._this.getProperty("tencent_cdn.pull_live");
        String pushAuthKey = getAuthKey("pull");
        if(pushAuthKey == null){
            return null;
        }
        String safeKey = getSafeUrl(pushAuthKey,liveId+"",null);
        String input = new StringBuilder().
                append("https://"+pull_domain+"/").
                append("live/").
                append(liveId+".m3u8?").
                append(safeKey).toString();
        return input;
    }

    private static String getSafeUrl(String key, String streamName, Long txTime) {
        if(txTime==null){
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY)+ 12);
            txTime = calendar.getTimeInMillis()/1000;
        }
        String input = new StringBuilder().
                append(key).
                append(streamName).
                append(Long.toHexString(txTime).toUpperCase()).toString();
        String txSecret = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            txSecret  = byteArrayToHexString(
                    messageDigest.digest(input.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return txSecret == null ? "" :
                new StringBuilder().
                        append("txSecret=").
                        append(txSecret).
                        append("&").
                        append("txTime=").
                        append(Long.toHexString(txTime).toUpperCase()).
                        toString();
    }

    private static String byteArrayToHexString(byte[] data) {
        char[] out = new char[data.length << 1];
        for (int i = 0, j = 0; i < data.length; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }

    /**
     * @param type push pull获取推流或者拉流鉴权key
     * @return
     */
    public String getAuthKey(String type) {
        String secretId = SysConfig._this.getProperty("tencent_cdn.secret_id");
        String secretKey = SysConfig._this.getProperty("tencent_cdn.secret_key");
        String push_domain = SysConfig._this.getProperty("tencent_cdn.push_live");
        String pull_domain = SysConfig._this.getProperty("tencent_cdn.pull_live");
        try{
            Credential cred = new Credential(secretId, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("live.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            LiveClient client = new LiveClient(cred, "", clientProfile);
            if(type.equalsIgnoreCase("push")){
                DescribeLivePushAuthKeyRequest req = new DescribeLivePushAuthKeyRequest();
                req.setDomainName(push_domain);
                DescribeLivePushAuthKeyResponse resp = client.DescribeLivePushAuthKey(req);
                return resp.getPushAuthKeyInfo().getMasterAuthKey();
            }else{
                DescribeLivePlayAuthKeyRequest req = new DescribeLivePlayAuthKeyRequest();
                req.setDomainName(pull_domain);
                DescribeLivePlayAuthKeyResponse resp = client.DescribeLivePlayAuthKey(req);
                return resp.getPlayAuthKeyInfo().getAuthKey();
            }

        } catch (TencentCloudSDKException e) {
            logger.error("LiveAuth.getAuthKey type:"+type+",error:{}",e);
        }
        return null;
    }

}
